#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>   
#include <time.h>
#include <pthread.h>

#include "tcp_server.h"
#include "process.h"
#include "common.h"
#include "bus_socket.h"
#include "massege.h"

ARG info;  

int is_connected = 0;
int send_msg(int nsockfd,const char* buf, int len,int flags)
{
	int num = 0;
	/*
	fd_set fds; 
	struct timeval timeout={3,0};

	FD_ZERO(&fds); 
	FD_SET(nsockfd,&fds); 

	while(FD_ISSET(nsockfd,&fds))
	*/
	//{
		//re = select(nsockfd+1,&fds, NULL, NULL,&timeout)
	//if(is_connected)
	{
		if((num = send(nsockfd, buf, len, 0)) == -1)
		{
			printf("ERROR: Failed to sent in send_msg.\n");
		}
	}
	/*
	printf("OK: Sent %d bytes sucessful.\n", num);
	for(int i=0; i<num; i++)
	{
		printf("%X,",(unsigned char)sdbuf[i]);
	}
	*/
	
	return num;

}



void thread_receive(int nsockfd)  
{  
    int num = 0;  
    char recvbuf[LENGTH];
	fd_set fds; 
	struct timeval timeout={1,0};
	int re = 0;
	int data_len = 0;
	int recv_len = 0;
	struct sockaddr_in *client = get_connect_client(); 
	
    while (1)
	{ 
		FD_ZERO(&fds);
	    FD_SET(nsockfd,&fds);

		switch(re = select(nsockfd+1,&fds, NULL, NULL,&timeout))
        { 
            case -1: 
				printf("ERROR: %s socket select error!\n",inet_ntoa(client->sin_addr));
				is_connected = 0;
				close(nsockfd);
				return;
            case 0:
				//printf("Connection lost.\n");
				//close(nsockfd);
				break;
            default: 
                if(FD_ISSET(nsockfd,&fds))
                {
					memset (recvbuf,0,LENGTH);
					num = recv(nsockfd, recvbuf, LENGTH, 0);
					printf ("OK: Receviced numbytes = %d\n", num);
					if(num>0)
					{
						recv_len= num;
						if((unsigned char)recvbuf[2] == CMD_PIC)
						{							
							memcpy(&data_len,&recvbuf[3],sizeof(data_len));
							while(recv_len<(data_len+9))
							{
								num = recv(nsockfd, &recvbuf[recv_len], LENGTH, 0);
								printf ("OK: Receviced more numbytes = %d\n", num);
								recv_len= recv_len +num;
							}
						}

						parase_cmd(recvbuf,recv_len);
					}
					else
					{
						printf("ERROR: %s network is lost!\n",inet_ntoa(client->sin_addr));
						is_connected = 0;
						close (nsockfd);
						return;
					}
                }
        }
    }      
}
  
void* start_receive(void* arg)  
{  
	is_connected = 1;
    set_connect_info((ARG *)arg);
    thread_receive(get_connect_sockfd());  
    free(arg);
	set_time_out();
    pthread_exit(NULL);  
}   


void set_connect_info(ARG * arg)
{
	memset(&info,0,sizeof(ARG));
	info.connfd = arg->connfd;  
    memcpy(&(info.client), &arg->client, sizeof(struct sockaddr_in)); 
}

ARG * get_connect_info()
{
	return &info;
}

int get_connect_sockfd()
{
	return info.connfd;
}

struct sockaddr_in* get_connect_client()
{
	return &info.client;
}



